package com.lyz.file.impl;


import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

import com.lyz.file.IFileFetcher;
import com.lyz.file.IFileQueue;
import com.lyz.util.BaseTypeUtil;
//import com.lyz.util.PropertiesUtil;
import com.lyz.util.SleepUtil;

/**
 * 文件队列，每种日志文件都需要一个相应的队列，以支持多中文件的传送
 * 
 * @author luyongzhao
 * 
 */

public class LogFileQueue implements IFileQueue {

	private final static Logger logger = Logger.getLogger(LogFileQueue.class);

	private LinkedBlockingQueue<String> queue = null;

	/* 文件队列的长度，实时传输的文件不需要在等待队列中存放太多文件，
	 * 队列太长，可能会导致内存溢出*/
	private final int QUEUE_LENGTH = 5000;
	/*记录最后一个被加入队列的文件*/
	private String lastOne = null;

	public LogFileQueue() {
		queue = new LinkedBlockingQueue<String>(QUEUE_LENGTH);

	}
	/**
	 * 初始化文件队列，最少有一个文件被加入队列才结束
	 */
	public void initQueue(IFileFetcher fetcher) {
		/* 必须保证队列中至少有一个文件 */
		do {
			/* 初始化文件队列 */
			fetcher.initFileQueue();

			if (queue.isEmpty()) {
				/* 每隔5秒检测是否有新文件加入 */
				SleepUtil.sleepForCertainTime(5000);
				logger.info("retry to init queue...");
			}
		} while (queue.isEmpty());
	}


	@Override
	public String getNextFile() {

		String name = null;
		/* 以阻塞方式获取文件 */
		try {
			synchronized (queue) {
				name = queue.take();		
			}
			
		} catch (InterruptedException e) {
			logger.error("", e);
		}

		return name;
	}

	@Override
	public void addFile(String filePath) {

		if (filePath == null || "".equals(filePath.trim())) {
			return;
		}
		try {
			synchronized (queue) {
				lastOne = filePath;
				queue.put(filePath);
			}	
		} catch (InterruptedException e) {
			logger.error("exception when put file into queue", e);
		}

	}

	@Override
	public boolean isEmpty() {

		return queue.isEmpty();
	}

	@Override
	public int getFileCount() {

		return queue.size();
	}

	@Override
	public String getLastOne() {
		
		synchronized (queue) {
			while(this.lastOne == null){
				SleepUtil.sleep(5000);
				logger.info("queue is empty, retry...");
			}
			return this.lastOne;
		}
	}

	@Override
	public int size() {
		return queue.size();
	}

	public static void main(String args[]) {
		System.out.println(BaseTypeUtil.getSubString(
				"m_client_vv_2013-05-21_18.log", "m_client_vv_", ".log"));
	}

}
